//蓝牙控制层
const app = getApp();
//蓝牙适配
class BLEAdapter {
  constructor(id = "") {
    this.id = id
    this.devices = []
    this.DEVICE = new Map()
  }
  //开启适配器
  openBLEAdapter() {
    console.log('openBLEAdapter');
    return wx.openBluetoothAdapter()
      .then(() => {
        console.log('蓝牙适配器开启成功')
        return { ret: true };
      },
        (err) => {
          console.log('开启适配器错误')
          return { ret: false, msg: err }
        },
      )
      .catch(err => {
        console.log('开启适配器异常', err)
        return { ret: false, msg: err }
      })
  }
  //开始扫描
  startScan() {
    this.onBluetoothDeviceFound()
    console.log('startScan')
    return wx.startBluetoothDevicesDiscovery({
    })
      .then((res) => {
        console.log('扫描中')
        console.log('startBluetoothDevicesDiscovery success', res)
        return { ret: true, msg: null };
      },
        (err) => {
          console.log('扫描reject')
          return { ret: false, msg: err }
        })
      .catch(() => {
        return { ret: false, msg: err }
      })
  }

  //适配状态获取
  getAdapterState(callback) {
    wx.getBluetoothAdapterState({
      success: res => {
        console.log(res)
      }
    });
  }
  //异常重启适配器
  getTheAdapterRestart() {
    wx.closeBluetoothAdapter({
      success: () => {
        this.onBluetoothAdapterStateChange(() => {
          if (!this.available) {
            wx.openBluetoothAdapter()
          }
        })
      }
    })
  }
  //获取设备信息
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        const key = device.deviceId
        if (device.name && device.deviceId) {
          this.DEVICE.set(key, device)
        }
      })
    })
  }
  //读取设备信息
  peekDeviceId() {
    let Device = this.DEVICE
    let scannedDevices = {}
    for (let devices of Device.values()) {
      const id = devices.deviceId;
      const name = devices.name;
      let key = id + name
      if (scannedDevices[key] || devices.name.includes('HQ-')) {
        scannedDevices[key] = devices;
      }
      return scannedDevices
    }
  }
  //停止扫描
  stopScan() {
    return wx.stopBluetoothDevicesDiscovery()
      .then(() => {
        console.log('停止扫描')
        return { ret: true, msg: null };
      },
        (err) => {
          console.log('停止扫描失败')
          return { ret: false, msg: err }
        },
      )
      .catch(err => {
        console.log('异常', err)
        return { ret: false, msg: err }
      })
  }
  //关闭适配
  closeBluetoothAdapter() {
    return wx.closeBluetoothAdapter()
      .then(() => {
        console.log('关闭适配器成功')
        this.scannedDevices = {}
        return { ret: true, msg: null };
      },
        (err) => {
          console.log('关闭适配器失败')
          return { ret: false, msg: err }
        },
      )
      .catch(err => {
        console.log('异常', err)
        return { ret: false, msg: err }
      })
  }
  //连接
  connect(deviceId) {
    const connecting = new BLEConnection(deviceId)
    console.log(deviceId)
    return connecting.connect()
  }
}

//蓝牙连接
class BLEConnection {
  constructor(deviceIdParam) {
    this.deviceId = deviceIdParam
  }
  //设备回调连接
  connect(deviceId) {
    return new Promise((resolve, reject) => {
      wx.createBLEConnection({
        deviceId: '',
        success: () => {
          resolve()
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  }
  getCharacteristics(deviceId, serviceId) {
    return new Promise((resolve, reject) => {
      wx.getBLEDeviceCharacteristics({
        deviceId,
        serviceId
      })
        .then(res => {
          resolve(res.characteristics)
        })
        .catch(err => {
          reject(err)
        })

    })
  }
  //成功连接
  connectSuccess(toConnectedDeviceId) {
    var that = this;
    app.globalData.connectedDeviceId = toConnectedDeviceId;
    setTimeout(() => {
    }, 500);
  }
  //获取设备服务
  getServiceId(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        return res.services[0].uuid
      }
    })
  }
  //获取蓝牙特征值
  getCharacteristics(deviceId, serviceId) {
    return new Promise((resolve, reject) => {
      wx.getBLEDeviceCharacteristics()
        .then(resolve)
        .catch(reject)
    })
  }
}
//蓝牙服务
class BLEService {
  constructor() {
    this.deviceId = ' '
    this.devices = {}
    this.getDeviceId()
      .then(deviceId => {
        this.deviceId = deviceId;
      });
  }



  //获取设备ID
  getDeviceId() {
    return new Promise((resolve, reject) => {
      wx.getBluetoothDevices()
        .then(res => {
          resolve(res.deviceId);
        })
        .catch(err => {
          reject(err);
        });
    });
  }
  getDevice(deviceId) {
    return this.devices[deviceId] // 根据id获取
  }
  //数据发送
  sendData() {
    const device = this.getDevice(this.deviceId)
    this.getDeviceId()
      .then(deviceId => {
        if (device) {
          device.connect()
        }
        return device.connect();
      })
      .then(() => {
        return wx.writeBLECharacteristicValue({
          deviceId: this.deviceId,
        });
      })
      .then(() => {
        device.disconnect();
      })
      .catch(err => {
        console.log('连接异常:', err);
        if (device) {
          device.disconnect();
        }
      });
  }
  onDataChange(callback) {
    wx.onBLECharacteristicValueChange(res => {
      const { deviceId, value } = res
      const data = { deviceId, value }
      callback(data)
    })
  }
}

module.exports = {
  BLEAdapter,
}